package com.eairlv.utils;

import com.eairlv.utils.access.UserInfoArgumentResolver;
import com.eairlv.utils.config.FeignInterceptor;
import com.eairlv.utils.config.MSFilter;
import com.eairlv.utils.config.MSInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.Charset;
import java.util.List;

/**
 * @author eairlv
 * @description
 * @date 15:32 2019/8/16
 */
@ConditionalOnProperty(prefix = "ms-interceptor", value = "enabled", matchIfMissing = true)
@EnableConfigurationProperties(MSInterceptorProperties.class)
public class MSInterceptorConfiguration {

    @Autowired
    MSInterceptorProperties msInterceptorProperties;

    @Autowired
    RestTemplate feignRestTemplate;

    @Bean
    FeignInterceptor feignInterceptor() {
        return new FeignInterceptor();
    }

    @Bean
    MSInterceptor msInterceptor() {
        return new MSInterceptor(msInterceptorProperties, feignRestTemplate);
    }

    @Bean
    MSFilter msFilter() {
        return new MSFilter(msInterceptorProperties);
    }

    @Bean
    UserInfoArgumentResolver userInfoArgumentResolver() {
        return new UserInfoArgumentResolver();
    }

    @Bean
    @LoadBalanced
    public RestTemplate feignRestTemplate() {
        return getRestTemplate();
    }

    @Bean
    public RestTemplate restTemplate() {
        return getRestTemplate();
    }

    /**
     * 构造支持中文的RestTemplate
     *
     * @return
     */
    private RestTemplate getRestTemplate() {
        RestTemplate restTemplate = new RestTemplate();
        // 解决中文乱码
        List<HttpMessageConverter<?>> converterList = restTemplate.getMessageConverters();
        HttpMessageConverter<?> converter = new StringHttpMessageConverter(Charset.forName("UTF-8"));
        converterList.add(0, converter);
        return restTemplate;
    }

}
